package com.zenithmind.news.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;

import lombok.extern.slf4j.Slf4j;

/**
 * 新闻服务Spring Security配置 - 重构后遵循单一职责原则
 * 专门负责Spring Security的安全配置，端点定义已分离到NewsEndpointConfig
 *
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Slf4j
@Configuration
@EnableWebSecurity
public class NewsSecurityConfig {



    /**
     * 新闻服务Spring Security配置
     * 使用NewsEndpointConfig中定义的端点配置
     */
    @Bean
    @Order(1)
    public SecurityFilterChain newsSecurityFilterChain(HttpSecurity http) throws Exception {

        http
            // 禁用CSRF保护
            .csrf(AbstractHttpConfigurer::disable)
            // 配置认证和授权规则
            .authorizeHttpRequests(authorize -> {
                // 允许API文档相关端点
                authorize.requestMatchers(NewsEndpointConfig.API_DOC_ENDPOINTS).permitAll();
                // 允许公开端点
                authorize.requestMatchers(NewsEndpointConfig.PUBLIC_ENDPOINTS).permitAll();
                // 编辑角色端点
                authorize.requestMatchers(NewsEndpointConfig.EDITOR_ENDPOINTS).hasAnyRole("EDITOR", "ADMIN");
                // 用户角色端点
                authorize.requestMatchers(NewsEndpointConfig.USER_ENDPOINTS).authenticated();
                // 管理员角色端点
                authorize.requestMatchers(NewsEndpointConfig.ADMIN_ENDPOINTS).hasRole("ADMIN");
                // 其他请求需要认证
                authorize.anyRequest().authenticated();
            })
            // 使用无状态会话
            .sessionManagement(session -> session
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            // 禁用OAuth2资源服务器功能
            .oauth2ResourceServer(AbstractHttpConfigurer::disable);

        return http.build();
    }

}
